package com.huang.ThreadLock;

class test{

    volatile  int num=0;//线程共用


    //线程私有  类似销售买房子  各自有各自的销售量  线程私有
    //  因为对某个线程来说是一致的  所以在线程池中  线程可以复用  导致该变量OOM  所以需要进行清空 remove();
    ThreadLocal<Integer> local=ThreadLocal.withInitial(()->{return 0;});
    public void buyHouse(){
        Integer value = local.get();
        value++;
        local.set(value);
    }
}


public class Demo2 {
    public static void main(String[] args) {
        test test = new test();

            new Thread(()->{
                try {
                    for (int i = 0; i <8; i++) {
                        test.buyHouse();
                    }
                    System.out.println("1m"+test.local.get());
                } finally {
                    test.local.remove();
                }
            }).start();


        new Thread(()->{
            try {
                for (int i = 0; i <86; i++) {
                    test.buyHouse();
                }
                System.out.println("2m"+test.local.get());
            } finally {
                test.local.remove();
            }
        }).start();


        new Thread(()->{
            try {
                for (int i = 0; i <1; i++) {
                    test.buyHouse();
                }
                System.out.println("3m"+test.local.get());
            } finally {
                test.local.remove();
            }
        }).start();


        System.out.println("main线程"+test.local.get());
    }

}
